import subprocess
from flask import Flask, render_template, request, jsonify
from datetime import datetime
from database import db, ServerIP
import pytz
from apscheduler.schedulers.background import BackgroundScheduler

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///ip_data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

def ping_ip(ip):
    """执行ping命令检测IP状态"""
    try:
        output = subprocess.check_output(['ping', '-c', '1', '-W', '1', ip],
                                       stderr=subprocess.STDOUT)
        return True
    except subprocess.CalledProcessError:
        return False

def check_all_ips():
    """周期性检测所有IP状态并更新数据库"""
    with app.app_context():
        servers = ServerIP.query.all()
        for server in servers:
            is_alive = ping_ip(server.ip_address)
            server.status = is_alive
            server.last_updated = datetime.now(pytz.timezone("Asia/Shanghai"))
        db.session.commit()

# 初始化定时任务
scheduler = BackgroundScheduler()
scheduler.add_job(func=check_all_ips, trigger='interval', minutes=5)
scheduler.start()

# 创建数据库表
with app.app_context():
    db.create_all()

@app.route('/')
def index():
    #servers = ServerIP.query.order_by(ServerIP.last_updated.desc()).all()
    servers = ServerIP.query.order_by(ServerIP.ip_address.asc()).all()
    return render_template('index.html', git_version=get_git_version(), servers=servers)

@app.route('/api/report', methods=['POST'])
def report_ip():
    data = request.get_json()

    # 验证必要字段
    if not data or 'ip_address' not in data:
        return jsonify({'error': 'Invalid data'}), 400

    # 更新或创建记录
    server = ServerIP.query.filter_by(ip_address=data['ip_address']).first()
    if not server:
        server = ServerIP(ip_address=data['ip_address'])

    server.server_type = data.get('server_type')
    server.status = data.get('status', True)
    server.arch = data.get('arch', 'Unknown')
    server.os = data.get('os', 'Unknown')
    server.compiler = data.get('compiler', 'Unknown')
    server.kernel = data.get('kernel', 'Unknown')
    server.location = data.get('location', 'Unknown')
    server.number = data.get('number', 'Unknown')
    #server.last_updated = datetime.utcnow()
    server.last_updated = datetime.now(pytz.timezone("Asia/Shanghai"))
    server.note = data.get('note')

    db.session.add(server)
    db.session.commit()

    return jsonify({'message': 'Report received successfully'}), 200

def get_git_version():
    try:
        # 获取最新tag + commit hash
        tag = subprocess.check_output(['git', 'describe', '--tags', '--always']).decode().strip()
        # 获取提交日期（格式：YYYYMMDD）
        date = subprocess.check_output(['git', 'log', '-1', '--format=%cd', '--date=format:%Y%m%d']).decode().strip()
        return f"{tag}-{date}"
    except Exception as e:
        print(f"获取Git版本失败: {str(e)}")
        return "Development Build"

if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=False)

